<?php

namespace app\thirdPay\logic;
use app\common\library\Excel;
use app\common\library\RedissLock;
use app\common\service\CommonSystemImportService;
use think\facade\Db;
use think\facade\Config;

class LianlianLogic
{


    /**
     * @desc 导入连连支付数据
     * @date 2024-06-05
     * @author  luckyXiong
     */
    public function import_info($params=[]){
        $key = 'import_info_lian::'.time();
        $redis_lock = new RedissLock();
        $lock = $redis_lock::lock($key, $redis_lock::UNBLOCK, 500);
        $trans_number             = getIsset($params,'trans_number');
        $amount                   = getIsset($params,'amount');
        $bank_number              = getIsset($params,'bank_number');
        $shop_name                = getIsset($params,'shop_name');
        $currency                 = getIsset($params,'currency');
        $status                   = getIsset($params,'status');
        $created_at               = getIsset($params,'created_at');
        $shop_info                = self::get_shop_info($amount);
        //数据入库逻辑
        $info = [
            'shop_id'        => $shop_info['shop_id']??0,
            'pay_id'         => $shop_info['pay_id']??0,
            'trans_number'   => $trans_number,
            'amount'         => $amount,
            'bank_number'    => $bank_number,
            'payer_name'     => 'TikTok Shop',
            'shop_name'      => $shop_name,
            'currency'       => $currency,
            'status'         => $status,
            'date'           => date('Y-m', strtotime($created_at)),
            'created_at'     => $created_at,
        ];
        $res = Db::name('bank_pay_lianlian')->insertGetId($info);
        $lock->unlock();
        $info['status'] = $res == 1 ? 1:2;
        return  $info;
    }


    /**
     * @desc   导入连连支付数据
     * @date    2024-06-05
     * @author  luckyXiong
     */
    public function uploadInfo($params){
        try{
            $result = CommonSystemImportService::staticModel()->operate_import_data([
                    $this,//当前对应的service
                    'save',//类型: template 下载模板; save :保存 导入
                    CommonSystemImportService::TYPE_IMPORT_LIAN_LIAN,
                    1,
                    $params
                ]
            );
        }catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }

    /**
     * @desc   导入连连支付数据
     * @date    2024-06-05
     * @author  luckyXiong
     */
    public function pay_list($params=[]){
        $shop_id   = $params['shop_id'] ?? '';
        $date      = $params['date'] ?? '';
        $create_time = $params['create_time'] ?? '';
        $limit     = $params['limit'] ?? 10;

        $where = [];

        if ($shop_id) {
            $where[] = ['shop_id', '=', $shop_id];
        }

        if ($date) {
            $where[] = ['date', '=', $date];
        }

        if ($create_time) {
            $createtimeArr = explode(',', $create_time);
            $where[] = ['created_at', '>=', $createtimeArr[0]];
            $where[] = ['created_at', '<=', $createtimeArr[1]];
        }

        $field = 'id,date,shop_id,trans_number,bank_number,payer_name,shop_name,amount,status as pay_status,currency,created_at as create_time';

        $res = Db::name('bank_pay_lianlian')
            ->field($field)
            ->where($where)
            ->order('created_at desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        $list = objectToArray($list);
        $shop_ids      = array_column($list,'shop_id');
        $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select()->toArray();
        $shopInfos_map = array_column($shopInfos,null,'id');
        foreach($list as $k=>$v){
            $shop_name                   = $shopInfos_map[$v['shop_id']]??[];
            $list[$k]['shop_name']       = $shop_name['name']??'';
            unset($list[$k]['created_at']);
        }


        $total_info   = Db::name('bank_pay_lianlian')->where($where)->field('id,amount')->select()->toArray();
        $total_amount = array_sum(array_column($total_info, 'amount'));
        $total_amount = getRes($total_amount);

        return [
            'list'          => $list,
            'total'         => $res->total(),
            'total_amount'  => $total_amount,
        ];
    }



    /**
     * @desc   导入连连支付数据
     * @date    2024-06-05
     * @author  luckyXiong
     */
    public function get_excel_row_data($row){
        return [
            'trans_number'      => empty($row['A'])? '': trim($row['A']),
            'amount'            => empty($row['E'])? '': trim($row['E']),
            'bank_number'       => empty($row['C'])? '': trim($row['C']),
            'shop_name'         => empty($row['K'])? '': trim($row['K']),
            'currency'          => empty($row['D'])? '': trim($row['D']),
            'status'            => empty($row['G'])? '': trim($row['G']),
            'created_at'        => empty($row['B'])? '': trim($row['B']),
        ];
    }



    /**
     * @desc 获取店铺信息
     * @date 2024-06-05
     * @author  luckyXiong
     */
    private function get_shop_info($amount=''){
        if(!$amount) return 0;
        return Db::name('bank_pay_info')->where(['currency'=>'CNH','amount'=>$amount])->field('shop_id,pay_id')->find();
    }

    /**
     * @desc 获取店铺信息
     * @date 2024-06-05
     * @author  luckyXiong
     */
    private function get_shop_name($shop_name=''){
        if(!$shop_name) return ['name'=>''];
        $name = strstr($shop_name, "-", true);
        return  ['name'=>$name];
    }



}